package ui

import (
	"fmt"
	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/widget"
	"strings"
	"time"
)

type DebugWindow struct {
	window   fyne.Window
	logText  *widget.TextGrid
	messages []string
}

func NewDebugWindow(app fyne.App) *DebugWindow {
	w := app.NewWindow("Debug")
	dw := &DebugWindow{
		window:   w,
		logText:  widget.NewTextGrid(),
		messages: make([]string, 0),
	}

	dw.createUI()
	return dw
}

func (dw *DebugWindow) createUI() {
	clearBtn := widget.NewButton("Clear", func() {
		dw.messages = nil
		dw.updateDisplay()
	})

	content := container.NewBorder(nil, clearBtn, nil, nil, dw.logText)
	dw.window.SetContent(content)
	dw.window.Resize(fyne.NewSize(600, 400))
}

func (dw *DebugWindow) Log(format string, args ...interface{}) {
	message := time.Now().Format("15:04:05.000 ") + fmt.Sprintf(format, args...)
	dw.messages = append(dw.messages, message)
	dw.updateDisplay()
}

func (dw *DebugWindow) updateDisplay() {
	text := strings.Join(dw.messages, "\n")
	dw.logText.SetText(text)
}

func (dw *DebugWindow) Show() {
	dw.window.Show()
}
